package main

import (
	"log"
	// 引入 mysql, gorm
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
)

// Product 测试
type Product struct {
	ID    uint `gorm:"primary_key"`
	Code  string
	Price uint
	// 指定 column name
	StatsCount uint `gorm:"column:statsCount"`
}

// 测试 gorm 的时候
func main1() {
	db, err := gorm.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/golang")

	db.LogMode(true)

	if err != nil {
		log.Panicln("failed to connect database: ", err.Error())
	}

	defer db.Close()

	if !db.HasTable(Product{}) {
		db.CreateTable(Product{})
	}

	// 自动迁移表，生成的表名为 products
	// db.AutoMigrate(&Product{})

	// create
	db.Create(&Product{
		Code:  "11",
		Price: 52,
	})

	// 保持查询结果之间相互独立，否则会相互影响到查询条件
	var product1 Product
	var product2 Product
	var product3 Product

	// Query by primary key
	db.First(&product1, 2)

	log.Printf("product is %+v\n", product1)

	// Query with where claure
	db.First(&product2, "price = ?", 52)

	log.Printf("price 52 product is %+v\n", product2)

	// Query with where claure
	db.First(&product3, "price = ?", 53)

	log.Printf("price 53 product is %+v\n", product3)

	// 使用 where 语句查询
	// db.Where("price = ?", 52).Find(&product)

	// log.Printf("price 52 product is %+v\n", product)

	// db.Where("price = ?", 53).Find(&product)

	// log.Printf("price 53 product is %+v\n", product)
}
